/*
 * Algorithm.java
 * 
 *  author: Daniel Rudigier
 *    date: 10.12.2008
 * 
 * 
 */
package at.syncme.framework;

/**
 * the algorithm super-class. each algorithm, regardless of conservative or
 * optimistic fashion, has to derive from this class
 * 
 * @author Daniel Rudigier
 */
public abstract class Algorithm implements Runnable {
    protected Game game;

    protected Network network;
        
    /**
     * constructor
     * 
     * @param g
     */
    protected Algorithm(Network nw) {
        this.network = nw;
        this.network.setAlgorithm(this);
    }
    
    /**
     * be a little bit lazy 
     * 
     * @param lazy
     */
    protected void beLazy(long lazy) {
        try {
            Thread.sleep(lazy);
        } catch (InterruptedException e) {
            // don't care
        }
    }
    
    /**
     * wait (for Christmas?).
     */
    protected void beFair() {
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param game
     *            to set
     */
    public void setGame(Game game) {
        this.game = game;
    }

    /**
     * event received
     * 
     * @param e
     */
    public abstract void eventReceived(final Event e);

    /**
     * send an event to all nodes
     * 
     * @param e
     */
    public void sendEvent(final Event e) {
        this.network.sendToAllNodes(e);
    }

    /**
     * for deferred synchronization. send back acknowledgment to origin
     * 
     * @param e
     */
    public void acknowledge(final Event e) {
        this.network.sendToNode(e.getOrigin(), e.acknowledge());
    }

    /**
     * for deferred synchronization. send back reject to origin
     * 
     * @param e
     */
    public void reject(final Event e) {
        this.network.sendToNode(e.getOrigin(), e.reject());
    }

}
